package cn.sangedon.trade.gateway.filter;

import cn.sangedon.review.common.domain.sys.SysAuthorize;
import cn.sangedon.trade.gateway.service.SysAuthorizeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter {
    @Autowired
    private SysAuthorizeService sysAuthorizeService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpCookie auth = exchange.getRequest().getCookies().getFirst("auth");
        AtomicReference<Boolean> verify = new AtomicReference<>(false);
        Optional.ofNullable(auth).ifPresent(e -> {
            verify.set(checkAuth(e.getValue()));
        });
        if (verify.get()) {
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.writeWith(Flux.just(response.bufferFactory().wrap("无权限，请联系管理员".getBytes(StandardCharsets.UTF_8))));
    }

    private boolean checkAuth(String auth) {
        if (StringUtils.isEmpty(auth)) {
            return false;
        }
        QueryWrapper<SysAuthorize> query = new QueryWrapper<>();
        query.eq("authorize_key", auth);
        query.eq("is_del", 1);
        SysAuthorize authorize = sysAuthorizeService.getOne(query);
        return authorize != null;
    }
}
